package com.maple.admin.misc.menu.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.maple.admin.misc.menu.dto.MenuDTO;

/**
 * helper class to generate menu data
 * @author luoby
 * @since 1.7
 */
public class MenuHelper {
	
	static List<MenuDTO> _saved = new ArrayList<MenuDTO>();
	
	/**
	 * direct call to generate complete menu
	 * @param origin
	 * @return
	 */
	public static List<Object> generateMenu(List<MenuDTO> origin) {
		List<Object> resultList = new ArrayList<Object>();
		_saved = origin;
		for(MenuDTO menu: origin){
			Map<String,Object> _item = new LinkedHashMap<String,Object>();
			if(menu.getParent() == null){
				_item.put("id", menu.getDisplayNo());
				_item.put("text", menu.getText());
				_item.put("icon", menu.getIcon());
				if (menu.getIsHeader().equals(Boolean.TRUE)) {
					_item.put("isHeader", menu.getIsHeader());
				}
				List<?> children =  getRecursiveMenu(menu.getId().toString());
				if (children != null && children.size() > 0) {
					_item.put("children", children);
				}
				resultList.add(_item);
			}
		}
		return resultList;	
	}
	
	/**
	 * get menu item by its id recursively 
	 * @param menuIdStr
	 * @return
	 */
	public static List<?> getRecursiveMenu(String menuIdStr){
		List<Object> resultList = new ArrayList<Object>();
		for(MenuDTO menu: _saved){
			Map<String,Object> _children = new LinkedHashMap<String,Object>();
			if (menu.getParent() != null) {
				if (menu.getParent().toString().equals(menuIdStr)) {
					_children.put("id", menu.getDisplayNo());
					_children.put("text", menu.getText());
					_children.put("icon", menu.getIcon());
					if (menu.getUrl() != null) {
						_children.put("url", menu.getUrl());
						_children.put("targetType", "iframe-tab");
					}
					List<?> child = getRecursiveMenu(menu.getId().toString());
					if (child != null) {
						_children.put("children", child);
					}
					resultList.add(_children);
				} 
			}
		}
		if (resultList.size() > 0) {
			return resultList;
		} else {
			return null;
		}
	}
	
}
